<?php
class User extends AppModel {
	var $name = 'User';
	
	public $actsAs = array('Acl' => 'requester');
	
	var $validate = array(
		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Username not be left empty'
			)
		),
        'password' => array(
            'notEmpty' => array(
                'rule' => array('passwordNotEmpty'),
                'message' => 'Password not be left empty'
            )
        ),
        'password_confirm' => array(
            'confirmPassword' => array(
                'rule' => array('confirmPassword'),
                'message' => 'Does not match password'
            )
        ),
        'email' => array(
            'email' => array(
                'rule' => array('email', true),
                'message' => 'Email is not valid'
            )
        ),
        'member_id' => array(
            'notEmpty' => array(
                'rule' => array('notempty'),
                'message' => 'Member must be selected'
            )
        )
	);

	var $belongsTo = array(
		'Member' => array(
			'className' => 'Member',
			'foreignKey' => 'member_id',
			'conditions' => '',
			'fields' => '',
			'order' => '',
            'dependent' => false
		),
		'Group' => array(
			'className' => 'group',
			'foreignKey' => 'group_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
	

    public function passwordNotEmpty($data) {
        $valid = true;
        if ($this->data['User']['password'] == Security::hash(Configure::read('Security.salt'))) {
            $valid = false;
        }
        
        return $valid;
    }

    public function confirmPassword($data) {
        $valid = false;
        if ($this->data['User']['password'] == Security::hash(Configure::read('Security.salt') . $data['password_confirm'])) {
            $valid = true;
        }
        
        return $valid;
    }
	
	public function parentNode() {
		if (!$this->id && empty($this->data)) {
			return null;
		}
		$data = $this->data;
		if (empty($this->data)) {
			$data = $this->read();
		}
		if (empty($data['User']['group_id'])) {
			return null;
		} else {
			return array('Group' => array('id' => $data['User']['group_id']));
		}
	}
	
	/**	
	 * After save callback
	 *
	 * Update the aro for the user.
	 *
	 * @access public
	 * @return void
	 */
	function afterSave($created) {
			if (!$created) {
				$parent = $this->parentNode();
				$parent = $this->node($parent);
				$node = $this->node();
				$aro = $node[0];
				$aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
				$this->Aro->save($aro);
			}
	}
}
?>